<template>
  <div class="filter-fixed-buttons">
    <!-- <el-button class="c-btn32" text>
      <CIcon type="c-xian-daochu"></CIcon>
    </el-button> -->
    <slot name="placeholderRight"></slot>
    <el-popover
      popper-class="c-column-field-setting__popover"
      width="220"
      trigger="click"
      v-if="props.enableFieldsSetting && props.tableFieldsSetting?.length"
    >
      <template #reference>
        <div>
          <CIconButton icon="c-xian-peizhilie" content="列字段配置"></CIconButton>
        </div>
      </template>
      <div class="c-column-field-setting">
        <div class="setting__title">
          <span class="setting__title-text">列字段配置</span>
          <span class="setting__title-reset" @click="handleReset">重置</span>
        </div>
        <div class="setting__body">
          <el-checkbox-group v-model="checkedColumnFields" @change="handleCheckboxChange">
            <template v-for="item in columnSettingList" :key="item.key || item.field">
              <template v-if="item.children?.length">
                <div class="setting__body-line"></div>
                <div class="setting__body-subtitle">{{ item.title }}</div>
                <el-checkbox
                  :label="item2.field"
                  :disabled="item2?.columnSettingConfig?.type === ColumnSettingTypeEnum.REQUIRED"
                  v-for="item2 in item.children"
                  :key="item2.key || item2.field"
                  >{{ item2.title }}</el-checkbox
                >
              </template>
              <template v-else>
                <div class="setting__body-line" v-if="item.showLine"></div>
                <el-checkbox
                  :label="item.field"
                  :disabled="item?.columnSettingConfig?.type === ColumnSettingTypeEnum.REQUIRED"
                  >{{ item.title }}</el-checkbox
                >
              </template>
            </template>
          </el-checkbox-group>
        </div>
      </div>
    </el-popover>
    <CIconButton
      icon="c-xian-shuaxin"
      @click="handleRefresh"
      content="刷新"
      v-if="props.isShowRefreshBtn"
    ></CIconButton>
  </div>
</template>

<script lang="ts" setup name="">
import { withDefaults, defineProps, defineEmits, defineExpose, ref, computed, nextTick } from 'vue';
import { ColumnSettingTypeEnum, SearchBarTableFieldsSettingType } from './search-bar-fixed-buttons';
import { useMessage } from '@/hooks/useMessage';
import type { TableFieldsSettingType } from '../../PageTable';

interface SearchBarFixedButtonsProps {
  tableFieldsSetting: TableFieldsSettingType[];
  enableFieldsSetting: boolean;
  isShowRefreshBtn?: boolean;
  isShowSettingBtn?: boolean;
}

const props = withDefaults(defineProps<SearchBarFixedButtonsProps>(), {
  isShowRefreshBtn: true,
  isShowSettingBtn: true
});
const emits = defineEmits(['refresh', 'update:tableFieldsSetting', 'update:visible']);

const { createMessage } = useMessage();
const sourceColumnSetting = ref<TableFieldsSettingType[]>([]);

const localTableFieldsSetting = computed({
  get() {
    return props.tableFieldsSetting;
  },
  set(val) {
    console.log('localTableFieldsSetting', val);
    emits('update:tableFieldsSetting', val);
  }
});

const columnSettingList = computed<SearchBarTableFieldsSettingType[]>(() => {
  const res: SearchBarTableFieldsSettingType[] = [];
  let isLastGroup = false;
  for (const item of props.tableFieldsSetting) {
    if (item.columnSettingConfig?.type !== ColumnSettingTypeEnum.FIXED) {
      if (item.children?.length) {
        isLastGroup = true;
      } else if (isLastGroup === true) {
        // NOTE 如果上一个item是表头分组的最后一项，则当前item前需要加上一条线
        isLastGroup = false;
        (item as SearchBarTableFieldsSettingType).showLine = true;
      }
      res.push(item);
    }
  }
  return res;
});

const checkedColumnFields = ref();

// 初始化
function getSourceColumnSetting() {
  sourceColumnSetting.value = props.tableFieldsSetting;
  checkedColumnFields.value = getInitCheckedColumns(props.tableFieldsSetting);
}

/**
 * 获取初始选中的项
 * @param arr
 */
function getInitCheckedColumns(arr: TableFieldsSettingType[]): string[] {
  let res: string[] = [];
  for (const item of arr) {
    if (
      item.columnSettingConfig?.enabled &&
      item?.columnSettingConfig?.type !== ColumnSettingTypeEnum.FIXED
    ) {
      // field、key 两个中一定有一个
      res.push((item.field || item.key)!);
    }
    if (item.children?.length) {
      const childrenRes = getInitCheckedColumns(item.children);
      res = [...childrenRes, ...res];
    }
  }
  return res;
}

getSourceColumnSetting();

function handleRefresh() {
  emits('refresh');
}

function handleReset() {
  localTableFieldsSetting.value = sourceColumnSetting.value;
  // 需要update:tableFieldsSetting之后再传回来的props.tableFieldsSetting去做初始化
  nextTick(() => {
    checkedColumnFields.value = getInitCheckedColumns(props.tableFieldsSetting);
  });
}

// TODO 是否需要限制最少选择一项
const selectedList = ref<string[]>([]);
function handleCheckboxChange(val: string[]) {
  if (val.length === 0) {
    createMessage.error('至少包含一列');
    checkedColumnFields.value = selectedList.value;
    return;
  }
  selectedList.value = val;
  checkedColumnFields.value = val;
  localTableFieldsSetting.value = getLocalTableFieldsSetting(localTableFieldsSetting.value);
}

/**
 * 根据checkedColumnFields重新获取localTableFieldsSetting的值
 * @param arr
 */
function getLocalTableFieldsSetting(arr: TableFieldsSettingType[]) {
  const res: TableFieldsSettingType[] = [];
  for (const item of arr) {
    let columnSettingConfig: TableFieldsSettingType['columnSettingConfig'] =
      item.columnSettingConfig
        ? {
            ...item.columnSettingConfig
          }
        : undefined;
    if (
      columnSettingConfig &&
      item.columnSettingConfig?.type !== ColumnSettingTypeEnum.FIXED &&
      item.columnSettingConfig?.type !== ColumnSettingTypeEnum.REQUIRED
    ) {
      const enabled = checkedColumnFields.value.includes(item.field);
      columnSettingConfig.enabled = enabled;
    }
    // 这里会改变children的内容
    if (item.children?.length) {
      const childrenRes = getLocalTableFieldsSetting(item.children);
      item.children = childrenRes;
    }
    res.push({
      ...item,
      columnSettingConfig
    });
  }
  return res;
}

defineExpose({
  getSourceColumnSetting
});
</script>

<style lang="scss">
@use '../styles/search-bar-fixed-buttons.scss' as *;
</style>
